package com.yellowpage.mail.service;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.StringTokenizer;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import com.yellowpage.mail.bean.MailBean;
import com.yellowpage.white.exception.MailSendException;
import com.yellowpage.white.util.ObjectUtil;

public class MailSendServiceImpl implements MailSendService {
	private Log log = LogFactory.getLog(this.getClass());

	private JavaMailSenderImpl jmSenderImpl;
	// 邮箱用户名
	private String userName;
	// 邮箱密码
	private String password;
	// 发件人完整邮件地址
	private String from;

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getFrom() {
		return from;
	}

	public void setFrom(String from) {
		this.from = from;
	}

	public JavaMailSenderImpl getJmSenderImpl() {
		return jmSenderImpl;
	}

	public void setJmSenderImpl(JavaMailSenderImpl jmSenderImpl) {
		this.jmSenderImpl = jmSenderImpl;
	}

	/**
	 * 解析邮件地址
	 * 
	 * @param email
	 * @return
	 */
	public String[] setEmail(String email) {
		StringTokenizer st = new StringTokenizer(email, ";");
		String[] tokens = new String[st.countTokens()];
		int i = 0;
		while (st.hasMoreTokens()) {
			tokens[i] = st.nextToken();
			i++;
		}
		return tokens;
	}

	/**
	 * 设置附件
	 * 
	 * @param helper
	 * @param list
	 * @throws MessagingException
	 * @throws UnsupportedEncodingException
	 */
	public void setAttachment(MimeMessageHelper helper, List<String> list)
			throws MessagingException, UnsupportedEncodingException {
		if (null==list || list.size() == 0) {
			return;
		}

		for (String string : list) {
			File file = new File(string);
			if (!file.exists()) {
				continue;
			}
			if (file.isFile() && file.canRead()) {
				helper.addAttachment(MimeUtility.encodeWord(file.getName()),
						file);
			}
		}
	}

	@Override
	public void sendMail(MailBean mail) throws MailSendException {

		try {

			String result = ObjectUtil.isNull(mail.getUserName()) ? this.userName: mail.getUserName();
			jmSenderImpl
					.setUsername(ObjectUtil.isNull(mail.getUserName()) ? this.userName
					: mail.getUserName());
			jmSenderImpl
					.setPassword(ObjectUtil.isNull(mail.getPassWord()) ? this.password
							: mail.getPassWord());

			MimeMessage mailMessage = jmSenderImpl.createMimeMessage();
			MimeMessageHelper messageHelper = new MimeMessageHelper(
					mailMessage, true);

			if (!ObjectUtil.isNull(mail.getTo())) {
				messageHelper.setTo(this.setEmail(mail.getTo()));
			}

			if (!ObjectUtil.isNull(mail.getCc())) {
				messageHelper.setCc(this.setEmail(mail.getCc()));
			}
			if (null != mail.getBcc() && !mail.getBcc().trim().equals("")) {
				messageHelper.setBcc(this.setEmail(mail.getBcc()));
			}
			messageHelper.setFrom(ObjectUtil.isNull(mail.getFrom()) ? this.from
					: mail.getFrom());
			messageHelper.setSubject(mail.getSubject());
			
			messageHelper.setText(mail.getMessage(), false);
			this.setAttachment(messageHelper, mail.getAttachmentList());

			// 发送邮件
			jmSenderImpl.send(mailMessage);

		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw new MailSendException("发送邮件失败,失败原因为["+e.getMessage()+"]", e);
		}
	}

}
